//
//  HNHomeViewController.m
//  HappyNews
//
//  Created by baiping on 15/12/27.
//  Copyright © 2015年 bai wang. All rights reserved.
//

#import "HNHomeViewController.h"
#import "HNRequestManager.h"
#import "HNHomeMainModel.h"
#import "HNHomeMainHeaderView.h"
#import "UIButton+WebCache.h"
#import "HNHomeMainCell.h"
#import "MJRefresh.h"
#import "HNHomeNavigationBarView.h"
#import "HNUserViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "HNHomeDetialViewController.h"

#define iOS8_OR_LATER ([[UIDevice currentDevice] systemVersion].floatValue >= 8.0)
@interface HNHomeViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, HNHomeHeaderViewDelegate, HNUserViewControllerdDelegate, CLLocationManagerDelegate>

@property (nonatomic, strong) NSMutableArray *storiesArray;

@property (nonatomic, assign) NSInteger dateNumber;

@property (nonatomic, strong) NSString *datePar;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) HNHomeMainHeaderView *headView;

@property (nonatomic, strong) NSMutableDictionary *storiesDataDic;
// 由于数据存在这个字典里面是无序的 而新闻的展示是按日期排序的 所以添加一个数组记录key的排序
@property (nonatomic, strong) NSMutableArray *keys;

@property (nonatomic, strong) NSArray *dateArray;

@property (nonatomic, assign) BOOL  isleapYear;

@property (nonatomic, assign) NSInteger timePar;

@property (nonatomic, strong) NSArray *topStoriesArray;

@property (nonatomic, assign) NSInteger today;

@property (nonatomic, strong) NSArray *weekArray;

@property (nonatomic, strong) NSArray *weekArrayChinese;

@property (nonatomic, assign) BOOL isFrist;

@property (nonatomic, strong) NSString *dateStr;

@property (nonatomic, strong) NSMutableArray *keyOfNumber;

@property (nonatomic, strong) HNUserViewController *leftVC;

// 添加自定义导航栏view
@property (nonatomic, strong) HNHomeNavigationBarView *barView;

@property (nonatomic, strong) UIView *rightView;

// 创建一个定位管理
@property (nonatomic, strong) CLLocationManager *mgr;

// 创建一个反地理编码
@property (nonatomic, strong) CLGeocoder *geocoder;

// 给左视图添加一个导航控制器
@property (nonatomic, strong) UINavigationController *navigationVC;

// 详情界面的控制器
@property (nonatomic, strong) HNHomeDetialViewController *detialVC;

// 存放请求参数的数组
@property (nonatomic, strong) NSMutableArray *idArray;


@end

@implementation HNHomeViewController

// 懒加载存放参数的数组
- (NSMutableArray *)idArray{
    
    if (!_idArray) {
        
        _idArray = [NSMutableArray array];
        
    }
    return _idArray;
}
// 定位管理类懒加载
- (CLLocationManager *)mgr{
    
    if (!_mgr) {
        
        _mgr = [[CLLocationManager alloc]init];
        
        // 设置移动多少米 , 更新一次用户的位置
        _mgr.distanceFilter = 50;
        
        // 设置定位的精度
        _mgr.desiredAccuracy = kCLLocationAccuracyBest;
        
        _mgr.delegate = self;
        
        
    }
    return _mgr;
    
}
- (UIView *)rightView{
    
    if (!_rightView) {
        
        _rightView = [[UIView alloc]initWithFrame:self.view.frame];
        
        _rightView.backgroundColor = [UIColor whiteColor];
        
        [self.view addSubview:_rightView];
    }
    
    return _rightView;
    
}

- (NSArray *)weekArray{

    if (!_weekArray) {
        
        _weekArray = @[@"Mon", @"Tue", @"Wed", @"Thu", @"Fri", @"Sat", @"Sun"];
        
    }
    return _weekArray;
}

- (NSArray *)weekArrayChinese{
    
    if (!_weekArrayChinese) {
        
        _weekArrayChinese = @[@"星期一", @"星期二", @"星期三", @"星期四", @"星期五", @"星期六", @"星期日"];
        
    }
    return _weekArrayChinese;
}

- (NSArray *)topStoriesArray{
    
    if (!_topStoriesArray) {
        
        
        _topStoriesArray = [NSArray array];
        
    }
    return _topStoriesArray;
}

- (NSInteger )timePar{
    
    if (!_timePar) {
        
        NSDate *date = [NSDate date];
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        
        formatter.dateFormat = @"yyyyMMdd";
        
        NSString *dateStr = [formatter stringFromDate:date];
        
        _timePar = dateStr.integerValue;
    
    }
    
    return _timePar;
    
}
- (NSInteger )today{
    
    if (!_today) {
        
        NSDate *date = [NSDate date];
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        
        formatter.dateFormat = @"yyyyMMdd";
        
        NSString *dateStr = [formatter stringFromDate:date];
        
        _today = dateStr.integerValue;
    }
    
    return _today;
    
}
- (BOOL)isleapYear{
    
    NSDate *date = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    formatter.dateFormat = @"yyyyMMdd";
    
    NSString *dateStr = [formatter stringFromDate:date];
    
    NSString *yearStr = [dateStr substringToIndex:3];
    
    int year = yearStr.intValue;
    
    if ((year % 4 == 0 && year % 100 !=0)||year % 400 == 0){
        
        return YES;
    }else{
        
        return NO;
    }
}
- (NSArray *)dateArray{
    
    if (!_dateArray) {
        
        _dateArray = [NSArray array];
    
        if (_isleapYear) {
            
    _dateArray = @[@(31), @(29), @(31), @(30), @(31), @(30), @(31), @(31), @(30), @(31), @(30), @(31)];
            
        }else{
            
     _dateArray = @[@(31), @(28), @(31), @(30), @(31), @(30), @(31), @(31), @(30), @(31), @(30), @(31)];
            
        }
    }
    
    return _dateArray;
    
}
- (NSMutableDictionary *)storiesDataDic{
    
    if (!_storiesDataDic) {
        
        _storiesDataDic = [NSMutableDictionary dictionary];
        
    }
    
  return _storiesDataDic;

}
// 故事数组懒加载
- (NSMutableArray *)storiesArray{
    
    if (!_storiesArray) {
        
        _storiesArray = [NSMutableArray array];
    }
    return _storiesArray;
}

- (NSMutableArray *)keys{
    
    if (!_keys) {
        
        _keys = [NSMutableArray array];
    }
    
    return _keys;
}

- (NSMutableArray *)keyOfNumber{
    
    if (!_keyOfNumber) {
        
        
        _keyOfNumber = [NSMutableArray array];
        
    }
    return _keyOfNumber;
    
}
#pragma mark - 懒加载
- (CLGeocoder *)geocoder
{
    if (_geocoder == nil) {
        _geocoder = [[CLGeocoder alloc] init];
    }
    return _geocoder;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isFrist = YES;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self addTableView];
    
    [self addLastData];
    
    [self setupRefreshView];
   
    [self addNavigationBar];

    [self addLeftVC];
    
    // 注册通知
    //  获取通知中心(单例)
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    //  注册 并实现接到消息后的方法
    //  通知的名字 有规范: 一般 全部大写
    //  可以使用宏定义 写到全局头文件里
    [center addObserver:self selector:@selector(notification:) name:@"NIGHT" object:nil];
    
}

//  实现接到通知的方法
//  通知是通知中心发的 你接到是一个通知 而不是 通知中心
#pragma mark 改变皮肤的通知
- (void)notification:(NSNotification *)notification
{
    
    NSUserDefaults *defaluts = [NSUserDefaults standardUserDefaults];
    
    
    NSString *value = [defaluts objectForKey:@"Night"];

    
    for (int i = 0; i < self.keys.count; i++) {
        
        NSString *key = self.keys[i];
        
        NSArray *arr = self.storiesDataDic[key];
        
        for (HNHomeMainModel *model in arr) {
            
            model.isNight = ![value isEqualToString:@"YES"] ? 1 : 0;
            
        }
        
        [self.tableView reloadData];
    }

}
// 添加左视图控制器
- (void)addLeftVC{
    
    _leftVC = [[HNUserViewController alloc]init];
    
    _navigationVC = [[UINavigationController alloc]initWithRootViewController:_leftVC];
    
    _leftVC.navigationController.navigationBar.hidden = YES;
    
    _leftVC.delegate = self;
    
    [self.view insertSubview:_navigationVC.view belowSubview:self.rightView];
}

// 添加自定义navigationBar
- (void)addNavigationBar{
    
    self.navigationController.navigationBar.hidden = YES;
    
    _barView = [[HNHomeNavigationBarView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 64)];
    
    // 添加我的按钮
    [_barView.meBtn setBackgroundImage:[UIImage imageNamed:@"Home_Nomal"] forState:(UIControlStateNormal)];
    
     [_barView.meBtn setBackgroundImage:[UIImage imageNamed:@"Home_HeightLight"] forState:(UIControlStateHighlighted)];

    [self.rightView addSubview:_barView];
    
    _barView.backgroundColor = [UIColor whiteColor];
    
    // 给我的按钮添加点击方法
    [_barView.meBtn addTarget:self action:@selector(meBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    // 添加定位按钮的图片
    
     [_barView.changeLocation setImage:[UIImage imageNamed:@"Home_Location_UP"] forState:(UIControlStateNormal)];
    
     [_barView.changeLocation setImage:[UIImage imageNamed:@"Home_Location_Down"] forState:(UIControlStateSelected)];
    
    [_barView.locationBtn setTitleColor:[UIColor colorWithRed:77 / 256.0 green:167 / 256.0 blue:249 / 256.0 alpha:1.0] forState:(UIControlStateNormal)];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    NSString *currentCityName = [defaults valueForKey:@"currentCityName"];
    
    if (currentCityName) {
        
        [_barView.locationBtn setTitle:currentCityName forState:(UIControlStateNormal)];
        
        [_barView.locationBtn setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
      
        [_barView.locationBtn addTarget:self action:@selector(locationBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
        
    }else{
        
        NSString *title = @"定位";
        
        [_barView.locationBtn setTitle:title forState:(UIControlStateNormal)];
        // 根据title的值改变frame
        _barView.locationBtn.frame = [title rectwithFont:[UIFont systemFontOfSize:12] frame:_barView.locationBtn.frame];

        [_barView.locationBtn setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
        
        [_barView.locationBtn addTarget:self action:@selector(locationBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
        
        UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"定位城市" message:@"请点击定位定位到当前城市" preferredStyle:(UIAlertControllerStyleAlert)];
        
        UIAlertAction *agreeAction = [UIAlertAction actionWithTitle:@"知道了" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
    
        [alertView addAction:agreeAction];
        
        [self presentViewController:alertView animated:YES completion:nil];
    }
    
}
// 实现定位按钮的方法
- (void)locationBtnAction:(UIButton *)sender{
    
   // _barView.locationBtn.selected = !_barView.locationBtn.selected;
    
    // 实现定位功能
    if ([_barView.locationBtn.currentTitle isEqualToString:@"定位"]) {
        
        if ([self.mgr respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            
            [self.mgr requestAlwaysAuthorization];
            
        }
          [self.mgr startUpdatingLocation];
        
    }
    
    
}

#pragma mark -- 实现定位管理类的代理方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    
    // 取出用户的信息
    
    CLLocation *location = [locations lastObject];
    
    // 立即关闭定位 否则会耗电
    
    [self.mgr stopUpdatingLocation];
    
    // 反地理编码 得到当前城市

    [self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
      
        if (placemarks.count == 0 || error != nil) return ;
        
        CLPlacemark *placemark = [placemarks firstObject];
        
        // 根据定位到的城市改变按钮的frame
        _barView.locationBtn.frame = [placemark.subLocality rectwithFont:[UIFont systemFontOfSize:12] frame:_barView.locationBtn.frame];
        
        // 定位完成 添加提示框 提示用户是否定位到当前城市
        
        NSString *message = [NSString stringWithFormat:@"已定位到当前位置:%@%@ 是否定位", placemark.locality, placemark.subLocality];
        UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"定位城市" message:message preferredStyle:(UIAlertControllerStyleAlert)];
        
        UIAlertAction *agreeAction = [UIAlertAction actionWithTitle:@"好的" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
            [_barView.locationBtn setTitle:[NSString stringWithFormat:@"%@", placemark.subLocality] forState:(UIControlStateNormal)];
            
    
        }];
        
        UIAlertAction *voteAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
        
        [alertView addAction:agreeAction];
        
        [alertView addAction:voteAction];
        
        [self presentViewController:alertView animated:YES completion:nil];
 
    }];
    
    
}

#pragma mark ----- 实现userController的代理方法
- (void)userViewControllerBackHome{
    
    [self changeFrame];
}

// 实现我的按钮的点击方法

- (void)meBtnAction:(UIButton *)sender{
    
    [self changeFrame];
    
}

- (void)changeFrame{
    
    // 改变 view 的frame
    CGRect newFrame  = self.rightView.frame;
    
    CGRect tabBarNewFrame = self.tabBarController.tabBar.frame;
    
    // 如果 x为0就偏移到右侧 否则 就让 view复位
    if (newFrame.origin.x == 0) {
        
        newFrame.origin.x = kScreenWidth ;
        
        tabBarNewFrame.origin.x = kScreenWidth ;
        
        // [self.view addGestureRecognizer:_tap];
        
    }else{
        
        newFrame.origin.x = 0;
        
        tabBarNewFrame.origin.x = 0;
        
        //  [self.view removeGestureRecognizer:_tap];
    }
    [UIView beginAnimations:@"changeFrame" context:nil];
    
    [UIView setAnimationDuration:.5];
    
    [UIView setAnimationCurve:(UIViewAnimationCurveLinear)];
    
    self.rightView.frame = newFrame;
    
    self.tabBarController.tabBar.frame = tabBarNewFrame;
    
    [UIView commitAnimations];

}

- (NSString *)getNewDatePar{
    
    NSString *todayStr = [NSString stringWithFormat:@"%ld", self.timePar];
    
    
    NSInteger year = [todayStr substringToIndex:4].integerValue;
    
    
    NSRange range = NSMakeRange(4, 2);
    
    NSInteger month = [todayStr substringWithRange:range].integerValue;
    
    
    NSInteger day = [todayStr substringFromIndex:6].integerValue;
    
    day -= 1;
    
    
    if (day < 1) {
        
        month--;
        
        if (month < 1) {
            
            month = 12;
            
            year--;
            
            if ((year % 4 == 0 && year % 100 !=0)||year % 400 == 0){
                self.dateArray = @[@(31), @(29), @(31), @(30), @(31), @(30), @(31), @(31), @(30), @(31), @(30), @(31)];
            }else{
                
                self.dateArray = @[@(31), @(28), @(31), @(30), @(31), @(30), @(31), @(31), @(30), @(31), @(30), @(31)];
                
            }
            
        }
        
        day = (NSInteger)self.dateArray[month - 1];
    }
    
    
   return  [NSString stringWithFormat:@"%ld%02ld%02ld", year, month, day];

}
- (NSString *)datePar{
   
    NSString *dataStr = [self getNewDatePar];
    
    self.timePar = dataStr.integerValue;

    return dataStr;
    
}
// 下拉刷新
- (void)setupRefreshView
{
    __unsafe_unretained UITableView *tableView = self.tableView;
    
    // 上拉刷新
    tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self addMoreData];
        
        [tableView.mj_footer endRefreshing];
        
    }];

}

- (void)addLastData{
    
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    
    parDic = nil;
    
    [HNRequestManager requestWithUrlString:@"http://news-at.zhihu.com/api/4/stories/latest?client=0" parDic:parDic method:GET finish:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        
        NSArray *storiseArray = dic[@"stories"];
        
        NSMutableArray *storyTemp = [NSMutableArray array];
        
        for (NSDictionary *oneDic in storiseArray) {
            
            HNHomeMainModel *model = [[HNHomeMainModel alloc]init];
            
            [model setValuesForKeysWithDictionary:oneDic];
            
            [storyTemp addObject:model];
            
            [self.idArray addObject:model.number];
            
        }
        
         NSArray *topArray = dic[@"top_stories"];
        
         NSMutableArray *topTemp = [NSMutableArray array];
        
        for (NSDictionary *oneDic in topArray) {
            
            HNHomeMainModel *model = [[HNHomeMainModel alloc]init];
            
            [model setValuesForKeysWithDictionary:oneDic];
            
            [topTemp addObject:model];
            
            // 判断是否是夜间模式
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            
            NSString *value = [defaults stringForKey:@"Night"];
            
            model.isNight = [value  isEqual: @"YES"] ? 1 : 0;
   
        }
        self.topStoriesArray = topTemp;
        
        [self.storiesDataDic setValue:storyTemp forKey:@"last"];
        
        [self.keys addObject:@"last"];
        
        [self setScrollViewImage];
        
        [self.tableView reloadData];
        
        
    } error:^(NSError *error) {
        
    }];
    
}
// 下拉刷新
- (void)addMoreData{
    
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    
    parDic = nil;
   
    if (_isFrist == YES) {
        
        _dateStr = [NSString stringWithFormat:@"%ld", self.today];
        
        _isFrist = NO;
        
    }else{
        
        _dateStr = [self datePar];
    }
    
    NSString *str = [NSString stringWithFormat:@"http://news-at.zhihu.com/api/4/stories/before/%@?client=0", _dateStr];
    
    [HNRequestManager requestWithUrlString:str parDic:parDic method:GET finish:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        
        NSArray *storiseArray = dic[@"stories"];
        
        NSMutableArray *tempArr = [NSMutableArray array];
        
        for (NSDictionary *oneDic in storiseArray) {
            
            HNHomeMainModel *model = [[HNHomeMainModel alloc]init];
            
            [model setValuesForKeysWithDictionary:oneDic];
            
            // 判断是否是夜间模式
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            
            NSString *value = [defaults stringForKey:@"Night"];
            
            model.isNight = [value  isEqual: @"YES"] ? 1 : 0;

            [tempArr addObject:model];
            
            // 将参数保存至数组中
            [self.idArray addObject:model.number];
        }
        
        [self.storiesDataDic setValue:tempArr forKey:_dateStr];
        
        [self.keys addObject:_dateStr];
        
        // 如果不存在在加入 存在在加入 那么下面就没有值了
        if (!self.keyOfNumber.count) {
            
            NSString *firstStr = [self getNewDatePar];
            
            [self.keyOfNumber addObject:firstStr];
            
            NSLog(@"%@", firstStr);
            
        }
        
        if (![_dateStr isEqualToString:[NSString stringWithFormat:@"%ld", self.today]]) {
            
            NSString *dateStr = [self getNewDatePar];
            
            NSLog(@"%@dateStr", dateStr);
            
            [self.keyOfNumber addObject:dateStr];
            
            NSLog(@"%ld", self.keyOfNumber.count);
            
        }
        [self setScrollViewImage];
        
        [self.tableView reloadData];
        
          } error:^(NSError *error) {
    }];

}


- (void)addTableView{
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 44, kScreenWidth, kScreenHeight - 44) style:(UITableViewStyleGrouped)];
    
    [self.rightView addSubview:_tableView];
    
    self.tableView.delegate = self;
    
    self.tableView.dataSource = self;
    
   // self.tableView.backgroundColor = HNNeightColor;
    
    _headView = [[HNHomeMainHeaderView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 220)];
    
    _tableView.tableHeaderView = _headView;
    
    _headView.delegate = self;
    
    _headView.mainScrollView.delegate = self;

   [_headView.pageControl addTarget:self action:@selector(pageControlAction:) forControlEvents:(UIControlEventValueChanged)];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    
    return self.keys.count;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSString *key = self.keys[section];
    
    NSArray *arr = self.storiesDataDic[key];
    
    return arr.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifier = @"myCell";
    HNHomeMainCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if(!cell){
        cell = [[HNHomeMainCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
        
    }

    NSString *key = self.keys[indexPath.section];
    
    NSArray *arr = self.storiesDataDic[key];
    
    HNHomeMainModel *model = arr[indexPath.row];
    
    NSString *navigationBarTitle = [self titleForSection:indexPath.section];
    
    _barView.titleLabel.text = navigationBarTitle;
    
    
    if (indexPath.section == 0) {
        
        
        _barView.titleLabel.text = @"     今日热闻";
    }
    
   // NSLog(@"%d", model.isNight);
    
    cell.model = model;
    
    // 判断是否是夜间模式 数据持久化
    if (model.isNight) {
        
       cell.contentLabel.textColor = [UIColor whiteColor];
        
        cell.backgroundColor = HNNeightColor;
        
    }else{
        
        cell.contentLabel.textColor = [UIColor blackColor];
        
        cell.backgroundColor = [UIColor whiteColor];
        
    }
    
    // 给model的夜间模式添加监听者
    [model addObserver:self forKeyPath:@"isNight" options:(NSKeyValueObservingOptionNew) context:(__bridge void * _Nullable)(indexPath)];
    
    
    return cell;
}
// 实现model的KVO方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    BOOL isNight = change[@"new"];
    
    HNHomeMainCell *cell = [self.tableView cellForRowAtIndexPath:(__bridge NSIndexPath *)context];
    if (isNight) {
        
        cell.contentLabel.textColor = [UIColor whiteColor];
        
        cell.backgroundColor = HNNeightColor;
        
    }else{
        
        cell.contentLabel.textColor = [UIColor blackColor];
        
        cell.backgroundColor = [UIColor whiteColor];
        
    }
    
   [object removeObserver:self forKeyPath:keyPath];
    
    
}
// 返回分区尾视图高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.0001;
    
}

// 返回分区头视图高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        return 0.00001;
    }
    
    return 30;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 90;
}

// 实现点击cell跳转的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    NSString *key = self.keys[indexPath.section];
    
    NSArray *arr = self.storiesDataDic[key];
    
    HNHomeMainModel *model = arr[indexPath.row];
    
    _detialVC = [[HNHomeDetialViewController alloc]init];
    
    _detialVC.number = model.number;
    
  
    for (int i = 0; i < indexPath.section; i++) {
        
        NSString *key = self.keys[i];
        
        NSArray *arr = self.storiesDataDic[key];
        
       
        _detialVC.currentIndex += arr.count;
        
    }
     // 传过去以后对应的数组中得值记得减一 但是这里已经减一了
    _detialVC.currentIndex += indexPath.row;
    
    _detialVC.idArray = self.idArray ;
    
    [self.navigationController pushViewController:_detialVC animated:YES];

}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 30)];
    
    label.textAlignment = NSTextAlignmentCenter;
    
    [view addSubview:label];
    
    NSString *title = [self titleForSection:section];
    
    
    label.text = title;
    
    return view;
}

// 传入分区返回分区标题
- (NSString *)titleForSection:(NSInteger)section{
    
    
    
    if (section == 0) {
        
        return 0;
    }else{
        
        NSString *key = self.keyOfNumber[section - 1];
        
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        
        fmt.dateFormat = @"yyyyMMdd";
        
        NSDate *date = [fmt dateFromString:key];
        
        fmt.dateFormat = @"EEE";
        
        
        NSString *week = [fmt stringFromDate:date];
        
        NSLog(@"%@", week);
        
        NSString *weekNew = @"";
        
        for (int i = 0; i < 7; i++) {
            
            if ([week isEqualToString:self.weekArray[i]]) {
                
                weekNew = self.weekArrayChinese[i];
                
            }
            
        }
        
        NSRange range = NSMakeRange(4, 2);
        
        NSString * month = [key substringWithRange:range];
        
        NSString *day = [key substringFromIndex:6];
        
        NSString *title = [NSString stringWithFormat:@"%@月%@日 %@", month, day, weekNew];
    
    
        return title;
    
}

}
// 添加轮播图按钮的图片
- (void)setScrollViewImage{
    
    HNHomeMainModel *FristModel = [self HNHomeModelForIndex:2];
    
    [_headView.fristScrollBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:FristModel.image] forState:(UIControlStateNormal)];
    
    HNHomeMainModel *SecondModel = [self HNHomeModelForIndex:0];
    
    [_headView.secondScrollBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:SecondModel.image] forState:(UIControlStateNormal)];
    
    
    HNHomeMainModel *ThirdModel = [self HNHomeModelForIndex:1];
    
    [_headView.thridScrollBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:ThirdModel.image] forState:(UIControlStateNormal)];
    
    
    HNHomeMainModel *FourModel = [self HNHomeModelForIndex:2];
    
    [_headView.fourScrollBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:FourModel.image] forState:(UIControlStateNormal)];
    
    // 给分页添加方法
    [_headView.pageControl addTarget:self action:@selector(pageControlAction:) forControlEvents:(UIControlEventValueChanged)];
}



- (HNHomeMainModel *)HNHomeModelForIndex:(NSInteger)index{
    
    return  self.topStoriesArray[index];
    
}

// 轮播的代理方法

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    
    if (scrollView == _headView.mainScrollView) {
        
        CGFloat width = scrollView.frame.size.width;
        
        CGFloat x = scrollView.contentOffset.x;
        
        if (x < 0) {
            
            [scrollView setContentOffset:CGPointMake(width * 3, 0) animated:NO];
        }
        
        if (x > width * 3) {
            
            [scrollView setContentOffset:CGPointMake(0, 0) animated:NO];
            
        }
        
    }
    
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView

{
    if (scrollView == _headView.mainScrollView) {
        
        
        CGFloat x = scrollView.contentOffset.x;
        CGFloat width = scrollView.frame.size.width;
        
        NSInteger page = x / width;
        
        if (page == 0) {
            
            _headView.pageControl.currentPage = 2;
            
        } else {
            _headView.pageControl.currentPage = page -  1;
        }
        
    }
}
// pageControll 的点击方法
- (void)pageControlAction:(UIPageControl *)pageControl
{
    
    NSInteger currentPage = pageControl.currentPage;
    
    CGFloat x = (currentPage + 1 ) * _headView.mainScrollView.frame.size.width;
    
    [_headView.mainScrollView setContentOffset:(CGPointMake(x, 0)) animated:YES];
    
}



// 实现轮播图按钮点击
- (void)scrollImageBtnDidClickWithIndex:(NSInteger)index{
    
  
    
    
}

- (void)dealloc
{
    //  移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NIGHT" object:nil];
    
    
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}



@end
